package com.bjsj.pro.tools;

import android.os.Handler;
import android.os.Message;

import java.lang.ref.WeakReference;

/**
 * Created by Joe on 2018/5/31 0031 10:18.
 * 功能:handler弱引用可以在一定程度上防止内存泄露
 */

public final class HandlerTools
{

    private HandlerTools() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    public static class HandlerHolder extends Handler {
        WeakReference<OnReceiveMessageListener> mListenerWeakReference;

        /**
         * 使用必读：推荐在Activity或者Activity内部持有类中实现该接口，不要使用匿名类，可能会被GC
         *
         * @param listener 收到消息回调接口
         */
        public HandlerHolder(OnReceiveMessageListener listener) {
            mListenerWeakReference = new WeakReference<>(listener);
        }

        @Override
        public void handleMessage(Message msg) {
            if (mListenerWeakReference != null && mListenerWeakReference.get() != null) {
                mListenerWeakReference.get().handlerMessage(msg);
            }
        }
    }

    /**
     * 收到消息回调接口
     */
    public interface OnReceiveMessageListener {
        void handlerMessage(Message msg);
    }
//碎片里面使用
//    static class MyHandler extends Handler {
//        WeakReference<Activity> mActivityReference;
//
//        MyHandler(Activity activity) {
//            mActivityReference= new WeakReference<Activity>(activity);
//        }
//
//        @Override
//        public void handleMessage(Message msg) {
//            final Activity activity = mActivityReference.get();
//            if (activity != null) {
//                mImageView.setImageBitmap(mBitmap);
//            }
//        }
//    }

}
